<template>
  <div class="map-panel">
    <div class="fixed-button">
      <el-button type="primary" :icon="Place" circle @click="show = !show"></el-button>
    </div>

    <transition name="el-fade-in">
      <div v-show="show" class="transition-box">
        <div class="search-input-wrap">
          <div class="search-input">
            <el-input v-model="keyword" type="textarea" :rows="3" placeholder="请输入要查询的地址, 可输入多个地址，每个地址占据一行"> </el-input>
          </div>
          <!-- <el-input v-model="keyword" :rows="2" type="textarea" placeholder="Please input" /> -->
          <div class="btns">
            <el-button type="primary" :icon="Search" @click="searchAddress()">查询</el-button>
            <!-- <el-button-group>
              <el-button type="danger" :icon="Minus" @click="clearInput">清输入</el-button>              
            </el-button-group> -->
            <el-button type="danger" :icon="CircleClose" @click="clearAllData">清所有</el-button>
            <el-button type="success" :icon="Download" @click="downLoadXls">下载</el-button>
          </div>
        </div>
        <div class="table-box">
          <el-table :data="tableData" border style="width: 100%" max-height="300" empty-text="数据为空" @row-click="tableRowClick">
            <el-table-column type="index" width="50" />
            <el-table-column prop="address" label="地址" show-overflow-tooltip />
            <el-table-column prop="lng" label="经度" width="150" show-overflow-tooltip />
            <el-table-column prop="lat" label="纬度" width="150" show-overflow-tooltip />
            <el-table-column label="操作" width="100" fixed="right" class-name="operation">
              <template #default="scope">
                <el-button title="复制" type="text" :icon="CopyDocument" :id="`copy-row-${scope.$index}`" @click="copy($event, `copy-row-${scope.$index}`, scope.row)"></el-button>
                <el-button title="删除当前行" type="text" @click.stop="deleteRow(scope.$index)" :icon="CircleClose"></el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </transition>
  </div>
</template>

<script>
import { ref, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { Edit, Search, Download, CircleClose, Place, CopyDocument, Minus } from '@element-plus/icons'
import XLSX from 'xlsx'
import clipboard from 'clipboard'

export default {
  props: ['map'],
  setup(props) {
    const show = ref(false)
    const keyword = ref('')
    const tableData = ref([])

    const searchAddress = () => {
      if (!keyword.value) {
        ElMessage({
          type: 'error',
          showClose: true,
          offset: 10,
          message: '请输入要查询的地址'
        })
        return
      }
      let keywords = keyword.value.split('\n')
      if (keywords.length > 10) {
        ElMessage({
          showClose: true,
          offset: 10,
          message: '单次查询不要超过10条',
          type: 'warning'
        })
        return
      }
      let options = {
        onSearchComplete: function (results) {
          if (local.getStatus() == BMAP_STATUS_SUCCESS) {
            const arr = results._pois.map((item) => {
              return {
                address: item.address,
                lng: item.point.lng,
                lat: item.point.lat
              }
            })
            tableData.value.push(...arr)
          }
        }
      }
      let local = new BMapGL.LocalSearch(props.map, options)
      keywords.forEach((k) => {
        local.search(k)
      })
      setTimeout(() => {
        keyword.value = ''
      }, 300)
      // console.log(keyword, props.map)
    }

    const tableRowClick = (row, column, event) => {
      props.map.clearOverlays()
      let newPoint = new BMapGL.Point(row.lng, row.lat)
      let marker = new BMapGL.Marker(newPoint)
      marker.addEventListener('click', function () {
        let infoWindow = new BMapGL.InfoWindow(`地址：${row.address}<br>经度：${row.lng}<br>纬度：${row.lat}`, {
          width: 300,
          height: 120,
          title: '地点'
        })
        props.map.openInfoWindow(infoWindow, newPoint) //开启信息窗口
      })
      props.map.addOverlay(marker)
      props.map.panTo(newPoint)
    }

    // 复制
    const copy = (event, id, row) => {
      // event.stopPropagation()
      let clip = new clipboard('#' + id, {
        text: () => {
          return `地址：${row.address},经度：${row.lng},纬度：${row.lat}`
        }
      })
      nextTick(() => {
        clip.on('success', (e) => {
          ElMessage({
            type: 'success',
            showClose: true,
            offset: 10,
            message: '已复制成功,内容为：' + e.text
          })
          // 释放内存
          clip.destroy()
        })
        clip.on('error', (e) => {
          // 不支持复制
          ElMessage({
            type: 'error',
            showClose: true,
            offset: 10,
            message: '该浏览器不支持自动复制'
          })
          // 释放内存
          clip.destroy()
        })
      })
    }

    // 删除行
    const deleteRow = (idx) => {
      tableData.value.splice(idx, 1)
    }

    // 清输入框
    const clearInput = () => {
      keyword.value = ''
    }

    // 清空所有数据
    const clearAllData = () => {
      keyword.value = ''
      tableData.value = []
      props.map.clearOverlays()
    }

    // 下载xls
    const downLoadXls = () => {
      if (!tableData.value.length) {
        ElMessage({
          type: 'error',
          showClose: true,
          offset: 10,
          message: '先去查询一些地址吧！'
        })
        return
      }
      var filename = '查询结果.xlsx'
      var ws_name = '数据'

      let data = [...tableData.value]
      data.unshift({ address: '地址', lng: '经度', lat: '纬度' })

      let wb = XLSX.utils.book_new()
      let ws = XLSX.utils.json_to_sheet(data, { skipHeader: true })
      //设置列宽
      ws['!cols'] = [{ wch: 50 }, { wch: 30 }, { wch: 30 }]

      /* add worksheet to workbook */
      XLSX.utils.book_append_sheet(wb, ws, ws_name)

      XLSX.writeFile(wb, filename)
    }

    return {
      show,
      keyword,
      tableData,
      Edit,
      Search,
      Download,
      CircleClose,
      Place,
      searchAddress,
      tableRowClick,
      clearInput,
      clearAllData,
      downLoadXls,
      CopyDocument,
      Minus,
      copy,
      deleteRow
    }
  }
}
</script>

<style lang="scss" scoped>
.map-panel {
  position: fixed;
  z-index: 20;
  right: 10px;
  top: 10px;
  padding-top: 40px;
}
.fixed-button {
  position: absolute;
  right: 0;
  top: 0;
}
.transition-box {
  padding: 10px 20px;
  border-radius: 4px;
  background-color: rgba(255, 255, 255, 0.8);
  margin-right: 20px;
  min-width: 800px;
}

.search-input-wrap {
  display: flex;
  align-items: center;
  justify-content: space-between;
  .search-input {
    flex: 1;
    padding-right: 20px;
  }
  .btns {
    display: flex;
    align-items: center;
    .el-button-group {
      margin: 0 5px;
    }
  }
}

.table-box {
  margin-top: 8px;
}
</style>
